package sms

import (
	"encoding/json"
	"fmt"
	"gitee.com/jokces/kit/global/glconf"
	"gitee.com/jokces/kit/typ"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"gopkg.in/gomail.v2"
)

type MegHandle struct {
	SMS *dysmsapi.Client
	cfg glconf.MsgConf
}

func NewMegHandle(cfg glconf.MsgConf) *MegHandle {
	rs := &MegHandle{}
	if cfg.AliSmsConf.Enable {
		client, err := dysmsapi.NewClientWithAccessKey(cfg.RegionId, cfg.AccessKey, cfg.AccessKeySecret)
		if err != nil {
			panic("加载短信配置异常:" + err.Error())
		}
		rs.cfg = cfg
		rs.SMS = client
		return rs
	}
	return rs
}

// SendSingleCode 发送单个短信的处理
func (ls *MegHandle) SendSingleCode(mobile, val string) (bool, string, error) {
	request := dysmsapi.CreateSendSmsRequest()      //创建请求
	request.Scheme = "https"                        //请求协议
	request.PhoneNumbers = typ.GlobalMobile(mobile) //接收短信的手机号码,86
	request.SignName = ls.cfg.SignName              //短信签名名称
	if typ.IsChinesePhone(mobile) {
		request.TemplateCode = ls.cfg.TempChId
	} else {
		request.TemplateCode = ls.cfg.TempEnId
	}
	par, err := json.Marshal(map[string]interface{}{ //定义短信模板参数（具体需要几个参数根据自己短信模板格式）
		"code": val,
	})
	request.TemplateParam = string(par) //将短信模板参数传入短信模板

	response, err := ls.SMS.SendSms(request) //调用阿里云API发送信息
	if err != nil {                          //处理错误
		return false, err.Error(), err
	}
	if response.Code == "OK" {
		return true, response.RequestId, nil
	}
	return false, "", fmt.Errorf(response.Message)
}

// SendHtml 发送邮件的处理
func (ls *MegHandle) SendHtml(subject, content string, to ...string) (bool, error) {
	return ls.send("text/html", subject, content, to...)
}

func (ls *MegHandle) SendText(subject, content string, to ...string) (bool, error) {
	return ls.send("text/plain", subject, content, to...)
}

func (ls *MegHandle) send(contentType, subject, content string, to ...string) (bool, error) {
	m := gomail.NewMessage()
	m.SetHeader("From", ls.cfg.EmailConf.User)
	m.SetHeader("To", to...) //主送
	//m.SetHeader("Cc", "qiujiahongde@163.com") //抄送
	//m.SetHeader("Bcc", "309284701@qq.com")  // 密送
	//m.SetAddressHeader("Cc", "dan@example.com", "Dan")
	m.SetHeader("Subject", subject)
	//发送html格式邮件。
	//text/html
	m.SetBody(contentType, content)
	//m.Attach("/home/Alex/lolcat.jpg")  //添加附件
	d := gomail.NewDialer(ls.cfg.EmailConf.Host, 465, ls.cfg.EmailConf.User, ls.cfg.EmailConf.Pass)
	if err := d.DialAndSend(m); err != nil {
		return false, err
	}
	return true, nil
}
